<template>
	<div class="coach-mine">
		<div class="mine-item">
			<!-- <p class="mine-avatar" @click="takePhotoPortrait">
				<em>
					<em class="mine-cover"><img :src="portraitPictureFile ? portraitPictureFile : 'https://newmefit.cn/resource/gym/base/base3.jpg'" class="mine-img" mode="aspectFill"></em>
					<span style="margin-left: 10rpx;font-size: 26rpx;">头像</span>
				</em>
				<i class="micon-1"></i>
			</p> -->
			<p class="mine-avatar" @click="takePhotoFc">
				<em>
					<em class="mine-cover"><img :src="faceImageFile ? faceImageFile : 'https://newmefit.cn/resource/gym/base/base3.jpg'" class="mine-img" mode="aspectFill"></em>
					<span style="margin-left: 10rpx;font-size: 26rpx;">头像</span>
				</em>
				<i class="micon-1"></i>
			</p>
			<uni-icons type="close" size="18" class="icon-close" @click.prevent.stop="deleteFaceImage" color='red'></uni-icons>
			<!-- <p>
				<span>身高</span>
				<input class="uni-input" placeholder="身高" v-model="coachDetail.stature" :disabled="false" type="number"/>cm
				<i class="micon-1"></i>
			</p>
			<p>
				<span>体重</span>
				<input class="uni-input" placeholder="体重" v-model="coachDetail.weight" :disabled="false" type="number"/>kg
				<i class="micon-1"></i>
			</p> -->
		</div>
		<div class="mine-item fix-padding">
			<div class="mine-title">简介</div>
			<div class="mine-content">
				<uni-easyinput :border="false" type="textarea" v-model="coachDetail.introduce" placeholder="请输入教练简介" maxlength="500"/>
			</div>
		</div>
		<div class="mine-item fix-padding">
			<div class="mine-title">个人风采</div>
			<div class="mine-content img-wrap">
				<div class="img-item" v-for="(item,index) in coachMienFile" :key="index">
					<img :src="item" mode="aspectFill">
				</div>
			</div>
		</div>
		<div class="mine-item fix-padding">
			<div class="mine-title">教练证书</div>
			<div class="mine-content img-wrap">
				<div class="img-item1" v-for="(item,index) in coachCertificateFile" :key="index">
					<img :src="item" mode="aspectFill">
				</div>
			</div>
		</div>
		<div class="mine-item fix-padding">
			<div class="mine-title">授课案例</div>
			<div class="mine-content img-wrap">
				<div class="img-item" v-for="(item,index) in teachCaseFile" :key="index">
					<img :src="item" mode="aspectFill">
				</div>
			</div>
		</div>
		<div class="footer">
      <span class="next" @click="submit">修改</span>
    </div> 
	</div>
</template>

<script>
import { mapGetters } from 'vuex'
import { coachDetailGet, getPublicUrl, listPublicUrl, coachEdit } from '@/api/manageApi'
import { baseUrl } from '@/config/config'
export default {
	data() {
		return {
			coachDetail: {
				phone: '',
        userName: '',
        gender: '',
        storeId: '',
        enableShow: '',
        roleCode: '',
        enabled: '',
        stature: '',
        weight: '',
        starLevel: '',
        introduce: '',
				courseIds: [],
        coachMienFileIds: [],
        coachCertificateFileIds: [],
        teachCaseFileIds: []
			},
			portraitPictureFileId: '',
			portraitPictureFile: '',
			faceImageFileId: '',
			faceImageFile: '',
			coachMienFile: [],
			coachCertificateFile: [],
			teachCaseFile: []
		}
	},
	computed: {
		...mapGetters(['userInfo', 'uniToken'])
	},
	onLoad() {
		this.getCoachDetail()
	},
	methods: {
		deleteFaceImage () {
      this.faceImageFileId = ''
      this.faceImageFile = ''
    },
		takePhotoPortrait() {
      // 调用uni.chooseImage API
      uni.chooseImage({
        count: 1, // 默认9，设置图片的数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相机还是相册，默认二者都有
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          this.portraitPictureFile = tempFilePaths[0]
          // 调用uni.uploadFile API上传图片
          var uuid = this.getuuid()
          var imgStrArr = tempFilePaths[0].split('/')
          var name = imgStrArr[imgStrArr.length - 1]
          var url = baseUrl + '/file/handle/uploadFile?explorerId=-1&parentId=-1&name=' + name + '&md5=' + uuid
          uni.uploadFile({
            url: url, // 服务器上传接口地址
            filePath: tempFilePaths[0],
            name: 'file', // 必须填写，后台用来接收文件
            header: {
              'Authorization': 'Bearer' + ' ' + this.uniToken,
              'Content-Type': 'multipart/form-data'
            },
            success: (uploadFileRes) => {
              console.log('upload success:', uploadFileRes)
							this.portraitPictureFileId = JSON.parse(uploadFileRes.data).data.fileId
							this.uShowToast('图片上传成功')
            },
            fail: (uploadFileErr) => {
              console.log('upload fail:', uploadFileErr);
              this.uShowToast('失败' + JSON.stringify(uploadFileErr))
              // 处理上传失败的结果
            }
          })
        },
        fail: (chooseImageErr) => {
          console.log('choose image fail:', chooseImageErr)
          // 处理选择图片失败的结果
        }
      })
    },
		takePhotoFc() {
      // 调用uni.chooseImage API
      uni.chooseImage({
        count: 1, // 默认9，设置图片的数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'], // 可以指定来源是相机还是相册，默认二者都有
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          this.faceImageFile = tempFilePaths[0]
          // 调用uni.uploadFile API上传图片
          var uuid = this.getuuid()
          var imgStrArr = tempFilePaths[0].split('/')
          var name = imgStrArr[imgStrArr.length - 1]
          var url = baseUrl + '/file/handle/uploadFile?explorerId=-1&parentId=-1&name=' + name + '&md5=' + uuid
          uni.uploadFile({
            url: url, // 服务器上传接口地址
            filePath: tempFilePaths[0],
            name: 'file', // 必须填写，后台用来接收文件
            header: {
              'Authorization': 'Bearer' + ' ' + this.uniToken,
              'Content-Type': 'multipart/form-data'
            },
            success: (uploadFileRes) => {
              console.log('upload success:', uploadFileRes)
							this.faceImageFileId = JSON.parse(uploadFileRes.data).data.fileId
							this.uShowToast('图片上传成功')
            },
            fail: (uploadFileErr) => {
              console.log('upload fail:', uploadFileErr);
              this.uShowToast('失败' + JSON.stringify(uploadFileErr))
              // 处理上传失败的结果
            }
          })
        },
        fail: (chooseImageErr) => {
          console.log('choose image fail:', chooseImageErr)
          // 处理选择图片失败的结果
        }
      })
    },
		getCoachDetail () {
      var params = {
        userId: this.userInfo.userId
      }
      coachDetailGet(params).then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data
          this.coachDetail = data
					this.portraitPictureFileId = data.portraitPictureFileId
          getPublicUrl({fileId:this.portraitPictureFileId}).then(response => {
            this.portraitPictureFile = response.data
          })
          this.faceImageFileId = data.faceImageFileId
          getPublicUrl({fileId:this.faceImageFileId}).then(response => {
            this.faceImageFile = response.data
          })
          listPublicUrl(data.coachMienFileIds).then(res => {
            for (var key in res.data) {
              this.coachMienFile.push(res.data[key])
            }
          })
          listPublicUrl(data.coachCertificateFileIds).then(res => {
            for (var key in res.data) {
              this.coachCertificateFile.push(res.data[key])
            }
          })
          listPublicUrl(data.teachCaseFileIds).then(res => {
            for (var key in res.data) {
              this.teachCaseFile.push(res.data[key]) 
            }
          })
        }
      })
    },
		submit () {
			const reg = /^[^<>"'|\\%]+$/
			if (!reg.test(this.coachDetail.introduce) && this.coachDetail.introduce) {
				this.uShowToast('简介不能包含非法字符：< > \" \' \\\ |%')
				return
			}
			if(this.coachDetail.introduce && this.coachDetail.introduce.length > 500){
				this.uShowToast('简介长度不能超过500字符')
				return
			}
			const reg1 = /^[0-9]\d*$/
			if (!reg1.test(this.coachDetail.stature) && this.coachDetail.stature) {
				this.uShowToast('身高必须是数字')
				return
			}
			if (!reg1.test(this.coachDetail.weight) && this.coachDetail.weight) {
				this.uShowToast('体重必须是数字')
				return
			}
			var params = {
				"userId": this.userInfo.userId,
				"coachCertificateFileIds": this.coachDetail.coachCertificateFileIds,
				"coachMienFileIds": this.coachDetail.coachMienFileIds,
				"courseIds": this.coachDetail.courseIds,
				"enableShow": this.coachDetail.enableShow,
				"enabled": this.coachDetail.enabled,
				"faceImageFileId": this.faceImageFileId,
				"gender": this.coachDetail.gender,
				"introduce": this.coachDetail.introduce,
				"phone": this.coachDetail.phone,
				"portraitPictureFileId": this.portraitPictureFileId,
				"roleCode": this.coachDetail.roleCode,
				"starLevel": this.coachDetail.starLevel,
				"stature": this.coachDetail.stature,
				"storeId": this.coachDetail.storeId,
				"teachCaseFileIds": this.coachDetail.teachCaseFileIds,
				"userName": this.coachDetail.userName,
				"weight": this.coachDetail.weight
			}
			// console.log(params)
			coachEdit(params).then((res) => {
				// console.log(res)
				this.uShowToast(res.msg)
			})
		},
    getuuid (len, radix) {
      var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
      var chars = CHARS
      var uuid = []
      var i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
      } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    }
	}
}
</script>

<style lang="scss">
.coach-mine {
	padding-bottom: 150rpx;
	.fr{
		float: right;
	}
	.micon-1{
		width: 10rpx;
		height: 18rpx;
		display: inline-block;
		background: url(../../static/right2.png) no-repeat 0 0;
		background-size: cover;
		// margin-left: 20rpx;
	}
	.mine-cover{
		width: 96rpx;
		height: 96rpx;
		// border-radius: 15rpx;
		display: inline-block;
		text-align: center;
		line-height: 96rpx;
	}
	.mine-img{
		max-width: 96rpx;
		max-height: 96rpx;
		vertical-align: middle;
		border-radius: 15rpx;
	}
	h1{
		width: 702rpx;
		margin: 32rpx auto 24rpx;
		font-weight: 400;
		font-size: 30rpx;
		color: #1E1E1E;
	}
	.mine-item{
		width: 702rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 16rpx 28rpx 16rpx;
		box-sizing: border-box;
		margin: 24rpx auto;
		position: relative;
		.icon-close{
			position: absolute;
			left: 106rpx;
			top: 0px;
			color: red;
			font-size: 24rpx;
		}
		p{
			margin: 36rpx 0;
			display: flex;
			align-items: center;
      justify-content: space-between;
			font-size: 28rpx;
			color: #838383;
			span{
				width: 230rpx;
				display: inline-block;
				font-size: 30rpx;
				color: #1E1E1E;
			}
		}
		.uni-input{
			width: 350rpx;
			font-size: 28rpx;
			color: #838383;
			text-align: right;
		}
		.uni-easyinput__content-textarea {
			width: 100% !important;
			height: 320rpx !important;
		}
		.is-input-border {
			border: none !important;
		}
		.mine-avatar{
			margin: 0;
			line-height: 96rpx;
		}
		.mine-title{
			padding: 32rpx 29rpx;
			border-bottom: 1rpx solid #eee;
			font-weight: 400;
			font-size: 30rpx;
			color: #1E1E1E;
		}
		.mine-content{
			padding: 29rpx;
			min-height: 160rpx;
		}
		.img-wrap{
			display: flex;
			flex-wrap: wrap;
			.img-item{
				width: 200rpx;
				height: 142rpx;
				// background: #F7F7F7;
				line-height: 142rpx;
				margin-right: 23rpx;
				text-align: center;
				border-radius: 10rpx;
				img{
					border-radius: 10rpx;
				}
			}
			.img-item1{
				width: 140rpx;
				height: 140rpx;
				line-height: 140rpx;
				// background: #F7F7F7;
				// border: 1px solid #EFEFEF;
				text-align: center;
				border-radius: 10rpx;
				margin-right: 29rpx;
				img{
					border-radius: 10rpx;
				}
			}
			.img-item2{
				width: 140rpx;
				height: 140rpx;
				line-height: 140rpx;
				text-align: center;
				border-radius: 10rpx;
				margin-right: 29rpx;
			}
			.img-item:nth-child(3n){
				margin-right: 0rpx;
			}
			.img-item1:nth-child(3n){
				margin-right: 0rpx;
			}
			.img-item2:nth-child(3n){
				margin-right: 0rpx;
			}
			img{
				max-width: 100%;
				max-height: 100%;
				vertical-align: middle;
			}
		}
	}
	.fix-padding{
		padding: 0rpx;
	}
	.footer{
    width: 750rpx;
    height: 128rpx;
    background: #FFFFFF;
    text-align: center;
    position: fixed;
    left: 0;
    bottom: 0;
		// display: none; 
    span{
      margin-top: 24rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      display: inline-block;
      border-radius: 40rpx;
      background: #FF5D3D;
      font-size: 32rpx;
      color: #FFFFFF;
    }
    .next{
      width: 646rpx;
    }
    .pre-step{
      width: 328rpx;
      background: #FFFFFF;
      border: 1px solid #FF5A20;
      color: #FF5A20;
      margin-right: 30rpx;
    }
    .next-step{
      width: 328rpx;
    }
  }
}
</style>
